package com.trover.myapplication.ui.home

import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.viewModelScope
import com.trover.myapplication.core.http.apimodel.Result
import com.trover.myapplication.core.ui.BaseViewModel
import com.trover.myapplication.core.util.CoroutinesDispatcherProvider
import com.trover.myapplication.entity.PlanEntity
import kotlinx.coroutines.launch

class HomeViewModel(
    private val repository: HomeRepository,
    private val provider: CoroutinesDispatcherProvider
) :
    BaseViewModel() {

    private val _uiState = MutableLiveData<PlanModel>()
    val uiState: LiveData<PlanModel>
        get() = _uiState

    private var limit = 20
    private var offset = 0

    fun getPlans() {
        viewModelScope.launch(provider.main) {
            when (val result = repository.getPlans("admin", limit, offset)) {
                is Result.Success -> {
                    emitPlanUiState(
                        needLogin = false,
                        showLoading = false,
                        showEnd = true,
                        showSuccess = result.data
                    )
                }
                is Result.Error.NoResponseError -> {
                    emitPlanUiState(needLogin = true, showError = result.toString())
                }
                else -> {
                    emitPlanUiState(showError = result.toString(), needLogin = false)
                }
            }
        }
    }

    private fun emitPlanUiState(
        showLoading: Boolean = false,
        showError: String? = null,
        showSuccess: PlanEntity? = null,
        showEnd: Boolean = false,
        isRefresh: Boolean = false,
        needLogin: Boolean? = null
    ) {
        val uiModel = PlanModel(showLoading, showError, showSuccess, showEnd, isRefresh, needLogin)
        _uiState.value = uiModel
    }


    data class PlanModel(
        val showLoading: Boolean = false,
        val showError: String? = null,
        val showSuccess: PlanEntity? = null,
        val showEnd: Boolean = false, // 加载更多
        val isRefresh: Boolean = false, // 刷新
        val needLogin: Boolean? = null
    )
}